/**
 *                            License
 * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS  
 * CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). 
 * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW.  
 * ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR  
 * COPYRIGHT LAW IS PROHIBITED.
 * 
 * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND  
 * AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE  
 * MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED 
 * HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
 * 
 */
package l1j.server.server.clientpackets;

import l1j.server.server.ClientThread;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.trade.L1Trade;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.serverpackets.S_TradeAddItem;

// Referenced classes of package l1j.server.server.clientpackets:
// ClientBasePacket

/**
 * 處理收到由客戶端傳來增加交易物品的封包
 */
public class C_TradeAddItem extends ClientBasePacket {
	private static final String C_TRADE_ADD_ITEM = "[C] C_TradeAddItem";

	public C_TradeAddItem(byte abyte0[], ClientThread client) throws Exception {
		super(abyte0);

		L1PcInstance pc = client.getActiveChar();
		if (pc == null) {
			return;
		}
		
		int itemid = readD();
		int itemcount = readD();
		
		if(itemcount <= 0 || itemcount > 2000000000){
			return;
		}
		L1ItemInstance item = pc.getInventory().getItem(itemid);
		if(item ==  null){
			return;
		}
		if(item.getCount() < itemcount  || item.isEquipped()){
			return;
		}
		if(!L1Trade.isItemMovable(pc, item)){
			return;
		}
		
		L1PcInstance tradingPartner = L1Trade.getInstance().getTradePartner(pc);
		if (tradingPartner == null) {
			L1Trade.getInstance().stopTrade(pc.getTradeID());
			return;
		}
		if(pc.getTradeID() != tradingPartner.getTradeID()){
			return;
		}
		if (pc.getTradeOk()) {
			return;
		}
		if (tradingPartner.getInventory().checkAddItem(item, itemcount) != L1Inventory.OK) { // 檢查容量與重量
			tradingPartner.sendPackets(new S_ServerMessage(270)); // \f1持っているものが重くて取引できません。
			pc.sendPackets(new S_ServerMessage(271)); // \f1相手が物を持ちすぎていて取引できません。
			return;
		}
		pc.getInventory().tradeItem(item, itemcount,
				pc.getTradeWindowInventory());
		pc.sendPackets(new S_TradeAddItem(item,
				itemcount, 0));
		tradingPartner.sendPackets(new S_TradeAddItem(item,
				itemcount, 1));
	}

	@Override
	public String getType() {
		return C_TRADE_ADD_ITEM;
	}
}
